"use strict";
/*jslint node:true*/
const path = require("path");
const os = require("os");
const moment = require("moment");
const args = require("args");

const dev = process.env.NODE_ENV == "development";

// 启动参数
args.option(["p", "port"], "启动端口");
args.option(["g", "pg"], "postgre 服务 URL");

// 微信小程序参数
args.option("wxDomain", "微信API Domain");
args.option("wxAppId", "微信小程序appid");
args.option("wxAppSecret", "微信小程序AppSecret");

// 七牛云存储参数
args.option("qnak", "qiniuAccessKey");
args.option("qnsk", "qiniuSecretKey");
args.option("qnbkt", "qiniuBucket");
args.option("qndmn", "qiniuDomain");
args.option("aqm", "安全帽接入用户信息");
args.option("puAqm", "安全帽接入用户信息(new)");
args.option("puApi", "安全帽平台api");
args.option("loginUrl", "登录url");
args.option("firstProjectsUrl", "第一个项目接口url");
args.option("secondProjectsUrl", "第二个项目接口url");
args.option("latestVersonUrl", "最新版本号id");
args.option("pepDraftUrl", "草稿接口url");
args.option("pepProcessUrl", "项目接口url");
args.option("projectUserInfo", "账号密码");
args.option("pomsLoginUserInfo", "登录账号密码");

args.option(["c", "camundaHost"], "camunda rest host");
args.option(["r", "camundaRoot"], "camunda rest root");

args.option("redisHost", "redisHost");
args.option("redisPort", "redisPort");
args.option("redisPswd", "redisPassword");

//日志
args.option(["k", "kafka"], "kafka 服务 URL");

const flags = args.parse(process.argv);

const DB = process.env.SERVICE_PLATFORM_DB || flags.pg;

// 七牛云存储参数
const QINIU_DOMAIN_QNDMN_RESOURCE =
  process.env.ANXINCLOUD_QINIU_DOMAIN_QNDMN_RESOURCE || flags.qndmn;
const QINIU_BUCKET_RESOURCE =
  process.env.ANXINCLOUD_QINIU_BUCKET_RESOURCE || flags.qnbkt;
const QINIU_AK = process.env.ANXINCLOUD_QINIU_ACCESSKEY || flags.qnak;
const QINIU_SK = process.env.ANXINCLOUD_QINIU_SECRETKEY || flags.qnsk;

//工作流
const FS_CAMUNDA_HOST = process.env.CAMUNDA_HOST || flags.camundaHost;
const FS_CAMUNDA_ROOT = process.env.CAMUNDA_ROOT || flags.camundaRoot;

// 微信小程序参数
const WX_DOMAIN = process.env.WX_DOMAIN || flags.wxDomain;
const WX_APP_ID = process.env.WX_APP_ID || flags.wxAppId;
const WX_APP_SECRET = process.env.WX_APP_SECRET || flags.wxAppSecret;

//安全帽
const AQM = process.env.AQM || flags.aqm;
const PU_AQM = process.env.PU_AQM || flags.puAqm;
const PU_API = process.env.PU_API || flags.puApi;
const LOGINURL =
  process.env.LOGINURL || flags.loginUrl || "https://pep-demo.anxinyun.cn";
const PROJECTUSERINFO =
  process.env.PROJECTUSERINFO || flags.processUserInfo || "yunweifuwu/1213456a";
const POMSlOGINUSERINFO =
  process.env.POMSlOGINUSERINFO ||
  flags.pomsLoginUserInfo ||
  "PomsAdmin/123456";
const FIRSTPROJECTSURL =
  process.env.FIRSTPROJECTSURL ||
  flags.firstProjectsUrl ||
  "https://peppm-test.anxinyun.cn/_api/rpm/project/reserve/reserve";
const SECONDPROJECTSURL =
  process.env.SECONDPROJECTSURL ||
  flags.secondProjectsUrl ||
  "https://peppm-test.anxinyun.cn/_api/rpm/project/orderForm?depId=all";
const PEPDRAFTURL =
  process.env.PEPDRAFTURL ||
  flags.pepDraftUrl ||
  "https://pepca-demo.anxinyun.cn/_api/process/drafts";
const LATESTVERSONURL =
  process.env.LATESTVERSONURL ||
  flags.latestVersonUrl ||
  "https://pepca-demo.anxinyun.cn/_api/workflow/process/630";
const PEPPROCESSURL =
  process.env.PEPPROCESSURL ||
  flags.pepProcessUrl ||
  "https://peppm-test.anxinyun.cn/_api/basic-data/workflow/complex/net/product/project/rpm";
// kafka
const KAFKA_LOGS = process.env.KAFKA_LOGS_BROKERS || flags.kafka;
// Redis 参数
const IOTA_REDIS_SERVER_HOST =
  process.env.IOTA_REDIS_SERVER_HOST || flags.redisHost || "redistest"; //redis IP
const IOTA_REDIS_SERVER_PORT =
  process.env.IOTA_REDIS_SERVER_PORT || flags.redisPort || "6378"; //redis 端口
const IOTA_REDIS_SERVER_PWD =
  process.env.IOTA_REDIS_SERVER_PWD || flags.redisPswd || ""; //redis 密码

//企业微信参数
const WXCHAT_REQURL =
  process.env.WXCHAT_REQURL || "https://qyapi.weixin.qq.com/cgi-bin";
const WXCHAT_AGENTID = process.env.WXCHAT_AGENTID || 1000012;
const WXCHAT_APPID = process.env.WXCHAT_APPID || "wxcba57321bee95eef"; //绑定的小程序id（只能绑定商用）
const WXCHAT_CORPID = process.env.WXCHAT_CORPID || "wwb729be4a7f781f75";
const WXCHAT_CORPSECRET =
  process.env.WXCHAT_CORPSECRET ||
  "JkzFbnl9fX0EvwSmV8inWir5vjV_m7lKyrjKwWft1gs";

const ALIBABA_CLOUD_ACCESS_KEY_ID = process.env.ALIBABA_CLOUD_ACCESS_KEY_ID;
const ALIBABA_CLOUD_ACCESS_KEY_SECRET =
  process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET;
const ALIBABA_CLOUD_FACE_DB_NAME = process.env.ALIBABA_CLOUD_FACE_DB_NAME ;
const ALIBABA_CLOUD_FACE_SCORE_THRESHOLD =
  process.env.ALIBABA_CLOUD_FACE_SCORE_THRESHOLD;
//消息通知自建应用

if (
  !DB ||
  !FS_CAMUNDA_HOST ||
  !FS_CAMUNDA_ROOT ||
  !KAFKA_LOGS ||
  !IOTA_REDIS_SERVER_HOST ||
  !IOTA_REDIS_SERVER_PORT
) {
  console.log("缺少启动参数，异常退出");
  args.showHelp();
  process.exit(-1);
}

const product = {
  port: flags.port || 8080,
  staticDirs: ["static"],
  mws: [
    {
      entry: require("@fs/attachment").entry,
      opts: {
        qiniu: {
          domain: QINIU_DOMAIN_QNDMN_RESOURCE,
          bucket: QINIU_BUCKET_RESOURCE,
          accessKey: QINIU_AK,
          secretKey: QINIU_SK,
        },
        maxSize: 104857600, // 100M
      },
    },
    {
      entry: require("./app/lib/middlewares/attachment.js").entry,
      opts: {
        qiniu: {
          accessKey: QINIU_AK,
          secretKey: QINIU_SK,
          bucket: QINIU_BUCKET_RESOURCE,
          domain: QINIU_DOMAIN_QNDMN_RESOURCE,
        },
        maxSize: 104857600, // 100M
        //  uploadPath: 'other'
      },
    },
    {
      entry: require("./app/lib/middlewares/alicloud-facebody-client.js").entry,
      opts: {
        accessKeyId: ALIBABA_CLOUD_ACCESS_KEY_ID,
        accessKeySecret: ALIBABA_CLOUD_ACCESS_KEY_SECRET,
      },
    },
    {
      entry: require("./app").entry,
      opts: {
        dev,
        exclude: [
          //    "*"
        ], // 不做认证的路由，也可以使用 exclude: ["*"]  跳过所有路由
        // clickHouse: {
        //    url: CLICKHOUST_URL,
        //    port: CLICKHOUST_PORT,
        //    user: CLICKHOUST_USER,
        //    password: CLICKHOUST_PASSWORD,
        //    db: [{
        //       name: 'alarm',
        //       db: 'alarm'
        //    },],
        // },
        weChat: {
          //企业微信配置
          reqUrl: WXCHAT_REQURL,
          agentid: WXCHAT_AGENTID,
          appid: WXCHAT_APPID, //绑定的小程序id
          corpid: WXCHAT_CORPID,
          corpsecret: WXCHAT_CORPSECRET,
          //   redirect_url: WXCHAT_REDIRECT_URL,
          //   schedule_corpsecret: WXCHAT_SCHEDULE_CORPSECRET,
        },
        aliCloud: {
          accessKeyId: ALIBABA_CLOUD_ACCESS_KEY_ID,
          accessKeySecret: ALIBABA_CLOUD_ACCESS_KEY_SECRET,
          faceDbName: ALIBABA_CLOUD_FACE_DB_NAME,
          faceScoreThreshold: ALIBABA_CLOUD_FACE_SCORE_THRESHOLD,
        },
        redis: {
          host: IOTA_REDIS_SERVER_HOST,
          port: IOTA_REDIS_SERVER_PORT,
          pwd: IOTA_REDIS_SERVER_PWD,
        },
        kafka: {
          rootURL: KAFKA_LOGS,
        },
        wx: {
          domain: WX_DOMAIN,
          appId: WX_APP_ID,
          appSecret: WX_APP_SECRET,
        },
        camundarest: {
          host: FS_CAMUNDA_HOST,
          root: FS_CAMUNDA_ROOT,
        },
        aqm: AQM,
        puAqm: PU_AQM,
        puApi: PU_API,
        loginUrl: LOGINURL,
        firstProjectsUrl: FIRSTPROJECTSURL,
        secondProjectsUrl: SECONDPROJECTSURL,
        projectUserInfo: PROJECTUSERINFO,
        pomsLoginUserInfo: POMSlOGINUSERINFO,
        pepDraftUrl: PEPDRAFTURL,
        latestVersonUrl: LATESTVERSONURL,
        pepProcessUrl: PEPPROCESSURL,
      },
    },
    // {
    //    entry: require('./app/lib/middlewares/proxy').entry,
    //    opts: {
    //       host: WATER_URL,
    //       match: /\/_water\//,
    //    }
    // },
    // {
    //    entry: require('./app/lib/middlewares/proxy').entry,
    //    opts: {
    //       host: WORKSAFETY_URL,
    //       match: /\/_worksafety\//,
    //    }
    // }
  ],

  dc: {
    url: DB,
    opts: {
      pool: {
        max: 80,
        min: 10,
        idle: 10000,
      },
      define: {
        freezeTableName: true, // 固定表名
        timestamps: false, // 不含列 "createAt"/"updateAt"/"DeleteAt"
      },
      timezone: "+08:00",
      logging: false,
    },
    models: [require("./app").models],
  },
  logger: {
    level: "info",
    json: false,
    filename: path.join(__dirname, "log", "runtime.log"),
    colorize: false,
    maxsize: 1024 * 1024 * 5,
    rotationFormat: false,
    zippedArchive: true,
    maxFiles: 10,
    prettyPrint: true,
    label: "",
    timestamp: () => moment().format("YYYY-MM-DD HH:mm:ss.SSS"),
    eol: os.EOL,
    tailable: true,
    depth: null,
    showLevel: true,
    maxRetries: 1,
  },
};

const development = {
  port: product.port,
  staticDirs: product.staticDirs,
  mws: product.mws,
  dc: product.dc,
  logger: product.logger,
};

if (dev) {
  // mws
  for (let mw of development.mws) {
    // if (mw.opts.exclude) mw.opts.exclude = ['*']; // 使用 ['*'] 跳过所有路由
  }
  // logger
  development.logger.filename = path.join(__dirname, "log", "development.log");
  development.logger.level = "debug";
  development.dc.opts.logging = console.log;
}

module.exports = dev ? development : product;
